﻿
    function ClockOn(mCategory, mActivity, mReason) {
        $.ajax({
            url: "/Common/ClockOn",
            type: 'POST',
            data: { category: mCategory, activity: mActivity, reason: mReason },
            success: function (response) {

                // enable resume previous task
                $("#btnResumePreviousTask").removeAttr("disabled");

                alert("Successfully clocked on!");

            },
            error: function (xhr) {
                alert("Error!");
            }
        });
    }


    /*  Get project list by user    */
    function GetProjectListByUserId(userId) {
        $.ajax({
            url: "/EnTimeLog/GetProjectPartialByUser",
            type: 'POST',
            data: { userId: userId },
            success: function (response) {
                $("#ajaxDropDownListProject").replaceWith(response);
                ClearGridData();
            },
            error: function (xhr) {
                alert("Error!");
            }
        });
    }

    /*  Get project detailed information    */
    function GetProjectDetail(pr_ref) {
        $.ajax({
            url: "/EnTimeLog/GetProjectDetail",
            type: 'POST',
            data: { projectId: pr_ref },
            success: function (response) {

                // Split response to array of values
                var array = response.split("#");

                // Replace old values with new ones
                $("#inputEngineer").val(array[0]);
                $("#inputLeadEngineer").val(array[1]);
                $("#inputToStart").val(array[2]);
                $("#inputToFinish").val(array[3]);
                $("#inputStatus").val(array[4]);
                $("#inputCompleted").val(array[5]);


            },
            error: function (xhr) {
                alert("Error!");
            }
        });
    }

    /*  Get project detailed information    */
    function GetLastProjectDetail() {
        $.ajax({
            url: "/EnTimeLog/GetLastProjectDetail",
            type: 'POST',
            data: { },
            success: function (response) {

                // Split response to array of values
                var array = response.split("#");

                // Replace old values with new ones
                $("#inputEngineer").val(array[0]);
                $("#inputLeadEngineer").val(array[1]);
                $("#inputToStart").val(array[2]);
                $("#inputToFinish").val(array[3]);
                $("#inputStatus").val(array[4]);
                $("#inputCompleted").val(array[5]);


            },
            error: function (xhr) {
                alert("Error!");
            }
        });
    }
    function GetProjectData() {
        if ($("select#ddlProject").val() != "-1" && $("select#ddlProject").val() != "" && $("select#ddlProject").val() != null) {

            // Get project referenced value
            var pr_ref = $("select#ddlProject").val();

            // Get project detailed info and categories, other engineers
            GetProjectDetail(pr_ref);

            // Ajax function
            $.ajax({
                url: "/EnTimeLog/GetTask",
                type: 'POST',
                data: {
                    projectId: pr_ref
                },
                success: function (response) {
                    $("#ajaxGridTask").replaceWith(response)
                },
                error: function (xhr) {
                    alert("Error!");
                }
            });

        }
        else {
            // Clear all grid's data
            ClearGridData();
        }
    }

    /*  Clear all grid data    */
    function ClearGridData() {
        $("#ajaxGridCategory").replaceWith("<div id='ajaxGridCategory'></div>");
        $("#ajaxGridTask").replaceWith("<div id='ajaxGridTask'></div>");
        $("#ajaxListOtherEngineers").replaceWith("<div id='ajaxListOtherEngineers'></div>");
    }

    /*  Get project list by user    */
    function CheckLastActualResourceUsage(url) {
        GetLoadingDialog();
        $.ajax({
            url: "/EnTimeLog/CheckLastActualResourceUsage",
            type: 'POST',
            data: {},
            success: function (response) {
                if (response == "WalkedOff" || response == "SwipedOut") {
                    /* user walked off */
                    if (response == "WalkedOff") {
                        GetWalkedOffDialog();
                    }
                    /* user swiped out but not clocked off */
                    if (response == "SwipedOut") {
                        GetSwipedOutButNotClockedOffDialog();
                    }
                    /* -------------- ---------------*/

                }
                // Response is empty -> Log on to last task
                else if (response != "null"){
                    LogOnToLastTask();
                }

                /* Close the loading dialog */
                CloseLoadingDialog();

            },
            error: function (xhr) {
                alert("Error!");
            }
        });
    }

    function LogOnToLastTask() {
        var r = confirm("Do you want to log on to your last task ?");
        var x = "";
        if (r == true) {
            // Ajax function
            $.ajax({
                url: "/EnTimeLog/LogOnToLastTask",
                type: 'POST',
                data: {
                },
                success: function (response) {
                    GetLoadingDialog();
                    LoadLastProject();
                    LoadLastTask();
                    LoadLastActualResourceUsages();
                    GetLastProjectDetail();
                    CloseLoadingDialog();
                    alert('Successfully logged on to your previous task');
                },
                error: function (xhr) {
                    alert("Error!");
                }
            });
        }
    }
    function LoadLastProject() {
        // Ajax function
        $.ajax({
            url: "/EnTimeLog/GetLastProject",
            type: 'POST',
            data: {
            },
            success: function (response) {
                $("#ajaxDropDownListProject").replaceWith(response)
            },
            error: function (xhr) {
                alert("Error!");
            }
        });
    }
    function LoadLastTask() {
        // Ajax function
        $.ajax({
            url: "/EnTimeLog/GetLastTask",
            type: 'POST',
            data: {
            },
            success: function (response) {
                $("#ajaxGridTask").replaceWith(response)
            },
            error: function (xhr) {
                alert("Error!");
            }
        });
    }
    function LoadLastActualResourceUsages() {
        // Ajax function load tasks
        $.ajax({
            url: "/EnTimeLog/GetLastActualResourceUsages",
            type: 'POST',
            data: {
            },
            success: function (response) {
                $("#ajaxGridActualResource").replaceWith(response);
            },
            error: function (xhr) {
                alert("Error loading actual resources!");
            }
        });
    }


    function GetLoadingDialog() {
        var dialog = $('#LoadingDialog');
        dialog.html('<div><img src="../../Images/ajax-loader.gif" /></div>');
        dialog.dialog({
            closeOnEscape: false,
            dialogClass: "no-title",
            bgiframe: true,
            resizable: false,
            modal: true,
            width: 250,
            height: 50
        });

    }
    function CloseLoadingDialog() {
        var dialog = $('#LoadingDialog');
        dialog.dialog("close");
    }

    // function Get Walked Off Dialog
    function GetWalkedOffDialog() {
        GetLoadingDialog();
        var dialog = $('#LogonModalDialog');
        $.get("/EnTimeLog/GetWalkedOffDialog", 
        { },
        function (responseText) {
            dialog.html(responseText);
            dialog.dialog({
                closeOnEscape: false,
                dialogClass: "no-close",
                bgiframe: true,
                resizable: false,
                modal: true,
                width: 450,
                buttons: {
                    // button OK
                    "OK": function () {
                        // Show Enter date dialog
                        GetEnterDateDialog();

                        // Close this dialog
                        $(this).dialog("close");
                    }
                }
                });
        });
        CloseLoadingDialog();
    }
    function GetEnterDateDialog() {
        GetLoadingDialog();
        var dialog = $('#EnterDateModalDialog');
        $.get("/EnTimeLog/GetEnterDateDialog",
        { },
        function (responseText) {
            dialog.html(responseText);
            dialog.dialog({
                dialogClass: "no-close",
                closeOnEscape : false,
                bgiframe: true,
                resizable: false,
                modal: true,
                width: 450,
                title: 'Enter your date',
                buttons: {
                    "OK": function () {
                        var date = $('#inputDate').val();
                        var time = $('#inputTime').val();
                        var fullDate = time + " " + date;
                        //var fullDate = date + " " + time;
                        UpdateLastActualResourceUsage(fullDate);
                        $(this).dialog("close");
                        LogOnToLastTask();
                    }
                }
            });
        });
        CloseLoadingDialog();
    }
    function GetSwipedOutButNotClockedOffDialog() {
        GetLoadingDialog();
        var dialog = $('#LogonModalDialog');
        $.get("/EnTimeLog/GetSwipedOutButNotClockedOffDialog",
        { },
        function (responseText) {
            dialog.html(responseText);
            dialog.dialog({
                closeOnEscape: false,
                dialogClass: "no-close",
                bgiframe: true,
                resizable: false,
                modal: true,
                width: 450,
                buttons: {
                    "Yes": function () {
                        GetEnterDateDialog();
                        $(this).dialog("close");
                    },
                    "No": function () {
                        // Close this dialog
                        $(this).dialog("close");
                        // Ask user to logon to last task
                        LogOnToLastTask();
                    }
                }
            });
        });
        CloseLoadingDialog();
    }
    function GetCurrentDate() {
        var objToday = new Date(),
                weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
                dayOfWeek = weekday[objToday.getDay()],
                domEnder = new Array('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'),
                dayOfMonth = today + (objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder[objToday.getDate()] : objToday.getDate() + domEnder[parseFloat(("" + objToday.getDate()).substr(("" + objToday.getDate()).length - 1))],
                months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
                curMonth = months[objToday.getMonth()],
                curMonth1 = objToday.getMonth(),
                curYear = objToday.getFullYear(),
                curDate = objToday.getDate(),
                curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
                curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
                curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
                curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
        var today = curHour + ":" + curMinute + ":" + curSeconds + " " + curMeridiem + " " + curMonth1 + "/" + curDate + "/" + curYear;
        return today;
    }

    /*  Get project list by user    */
    function UpdateLastActualResourceUsage(datetime) {
        if (datetime != null) {
                $.ajax({
                url: "/EnTimeLog/UpdateLastActualResourceUsage",
                type: 'POST',
                data: { dateTime: datetime },
                success: function (response) {
                    if (response != null && response != "") {
                        if (response == "-1") {
                            var message = "DateTime string was not in correct format !";
                            alert(message);
                        }
                        else {
                            //var message = "Successfully clocked off your task !";
                            //alert(message);
                        }
                    }
                },
                error: function (xhr) {
                    alert("Error!");
                }
            });
        }
    }

    function EndOfDay() {
            $.ajax({
                url: "/EnTimeLog/EndOfDay",
                type: 'POST',
                success: function (response) {
                    if (response != null && response != "") {
                        if (response == "-1") {
                            var message = "DateTime string was not in correct format !";
                            alert(message);
                        }
                        else {
                            var message = "Successfully clocked off your task !";
                            alert(message);
                        }
                    }
                },
                error: function (xhr) {
                    alert("Error!");
                }
            });
        }

